<script setup lang="ts">
import type {
  ActionStep,
  Behavior,
  BehaviorsFacet,
} from '#/api/resource-center/types';

import { computed, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

// Props
interface Props {
  behaviors?: BehaviorsFacet;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  update: [behaviors: BehaviorsFacet];
}>();

// 响应式数据
const behaviorModalVisible = ref(false);
const previewModalVisible = ref(false);
const editingBehavior = ref<Behavior | null>(null);
const previewBehaviorData = ref<Behavior | null>(null);

// 表单数据
const behaviorForm = reactive({
  id: '',
  name: '',
  kind: 'EXECUTION',
  retryPolicy: 'NONE',
  steps: [] as ActionStep[],
  emits: [] as string[],
});

// 计算属性
const behaviors = computed(() => props.behaviors || { definitions: [] });

// 方法
const getBehaviorKindColor = (kind: string) => {
  const colorMap: Record<string, string> = {
    EXECUTION: 'green',
    VALIDATION: 'blue',
    TRANSFORMATION: 'purple',
    NOTIFICATION: 'orange',
  };
  return colorMap[kind] || 'default';
};

const getBehaviorKindLabel = (kind: string) => {
  const labelMap: Record<string, string> = {
    EXECUTION: '执行',
    VALIDATION: '验证',
    TRANSFORMATION: '转换',
    NOTIFICATION: '通知',
  };
  return labelMap[kind] || kind;
};

const getStepDescription = (step: ActionStep) => {
  return `${step.type} - ${step.config || '无配置'}`;
};

const showAddBehaviorModal = () => {
  editingBehavior.value = null;
  resetBehaviorForm();
  behaviorModalVisible.value = true;
};

const editBehavior = (behavior: Behavior) => {
  editingBehavior.value = behavior;
  behaviorForm.id = behavior.id;
  behaviorForm.name = behavior.name;
  behaviorForm.kind = behavior.kind;
  behaviorForm.retryPolicy = behavior.retryPolicy || 'NONE';
  behaviorForm.steps = [...(behavior.steps || [])];
  behaviorForm.emits = [...(behavior.emits || [])];
  behaviorModalVisible.value = true;
};

const previewBehavior = (behavior: Behavior) => {
  previewBehaviorData.value = behavior;
  previewModalVisible.value = true;
};

const deleteBehavior = (behaviorId: string) => {
  const newDefinitions =
    behaviors.value.definitions?.filter((b) => b.id !== behaviorId) || [];
  emit('update', { ...behaviors.value, definitions: newDefinitions });
  message.success('行为删除成功');
};

const saveBehavior = () => {
  if (!behaviorForm.id || !behaviorForm.name) {
    message.error('请填写行为ID和名称');
    return;
  }

  const newBehavior: Behavior = {
    id: behaviorForm.id,
    name: behaviorForm.name,
    kind: behaviorForm.kind,
    retryPolicy: behaviorForm.retryPolicy,
    steps: [...behaviorForm.steps],
    emits: [...behaviorForm.emits],
  };

  const currentDefinitions = behaviors.value.definitions || [];
  let newDefinitions: Behavior[];
  newDefinitionsnewDefinitions;

  if (editingBehavior.value) {
    // 编辑模式
    newDefinitions = currentDefinitions.map((b) =>
      b.id === editingBehavior.value!.id ? newBehavior : b,
    );
  } else {
    // 新增模式
    newDefinitions = [...currentDefinitions, newBehavior];
  }

  emit('update', { ...behaviors.value, definitions: newDefinitions });
  message.success(editingBehavior.value ? '行为更新成功' : '行为创建成功');
  behaviorModalVisible.value = false;
};

const cancelBehavior = () => {
  behaviorModalVisible.value = false;
  resetBehaviorForm();
};

const resetBehaviorForm = () => {
  behaviorForm.id = '';
  behaviorForm.name = '';
  behaviorForm.kind = 'EXECUTION';
  behaviorForm.retryPolicy = 'NONE';
  behaviorForm.steps = [];
  behaviorForm.emits = [];
};

// 步骤编辑器方法
const addStep = () => {
  const stepId = `step_${Date.now()}`;
  behaviorForm.steps.push({
    id: stepId,
    type: 'API_CALL',
    config: '',
  });
};

const removeStep = (index: number) => {
  behaviorForm.steps.splice(index, 1);
};

const moveStep = (index: number, direction: 'down' | 'up') => {
  const steps = behaviorForm.steps;
  if (direction === 'up' && index > 0) {
    [steps[index], steps[index - 1]] = [steps[index - 1], steps[index]];
  } else if (direction === 'down' && index < steps.length - 1) {
    [steps[index], steps[index + 1]] = [steps[index + 1], steps[index]];
  }
};

// 事件编辑器方法
const addEvent = () => {
  behaviorForm.emits.push('');
};

const removeEvent = (index: number) => {
  behaviorForm.emits.splice(index, 1);
};
</script>

<template>
  <div class="resource-behaviors">
    <!-- 行为定义管理 -->
    <div class="behaviors-header">
      <h3>行为定义管理</h3>
      <a-button type="primary" @click="showAddBehaviorModal">
        <template #icon>
          <IconifyIcon icon="ant-design:plus-outlined" />
        </template>
        新增行为
      </a-button>
    </div>

    <!-- 行为列表 -->
    <div class="behaviors-content">
      <a-empty
        v-if="!behaviors?.definitions?.length"
        description="暂无行为定义"
      />

      <div v-else class="behaviors-list">
        <a-card
          v-for="behavior in behaviors.definitions"
          :key="behavior.id"
          class="behavior-card"
          :title="behavior.name"
        >
          <template #extra>
            <a-space>
              <a-tag :color="getBehaviorKindColor(behavior.kind)">
                {{ getBehaviorKindLabel(behavior.kind) }}
              </a-tag>
              <a-button
                type="link"
                size="small"
                @click="editBehavior(behavior)"
              >
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                @click="previewBehavior(behavior)"
              >
                预览
              </a-button>
              <a-popconfirm
                title="确定要删除这个行为吗？"
                @confirm="deleteBehavior(behavior.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>

          <div class="behavior-info">
            <p><strong>ID:</strong> {{ behavior.id }}</p>
            <p>
              <strong>类型:</strong> {{ getBehaviorKindLabel(behavior.kind) }}
            </p>
            <p><strong>步骤数:</strong> {{ behavior.steps?.length || 0 }}</p>
            <p>
              <strong>事件:</strong> {{ behavior.emits?.join(', ') || '无' }}
            </p>
          </div>

          <!-- 步骤预览 -->
          <div v-if="behavior.steps?.length" class="steps-preview">
            <h4>执行步骤</h4>
            <a-steps direction="vertical" size="small">
              <a-step
                v-for="(step, index) in behavior.steps"
                :key="step.id"
                :title="`${index + 1}. ${step.id}`"
                :description="getStepDescription(step)"
              />
            </a-steps>
          </div>
        </a-card>
      </div>
    </div>

    <!-- 新增/编辑行为模态框 -->
    <a-modal
      v-model:open="behaviorModalVisible"
      :title="editingBehavior ? '编辑行为' : '新增行为'"
      width="900px"
      @ok="saveBehavior"
      @cancel="cancelBehavior"
    >
      <a-form :model="behaviorForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="行为ID" name="id">
              <a-input
                v-model:value="behaviorForm.id"
                placeholder="请输入行为ID"
                :disabled="!!editingBehavior"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="行为名称" name="name">
              <a-input
                v-model:value="behaviorForm.name"
                placeholder="请输入行为名称"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="行为类型" name="kind">
              <a-select
                v-model:value="behaviorForm.kind"
                placeholder="请选择行为类型"
              >
                <a-select-option value="EXECUTION">执行</a-select-option>
                <a-select-option value="VALIDATION">验证</a-select-option>
                <a-select-option value="TRANSFORMATION">转换</a-select-option>
                <a-select-option value="NOTIFICATION">通知</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="重试策略" name="retryPolicy">
              <a-select
                v-model:value="behaviorForm.retryPolicy"
                placeholder="请选择重试策略"
              >
                <a-select-option value="NONE">不重试</a-select-option>
                <a-select-option value="IMMEDIATE">立即重试</a-select-option>
                <a-select-option value="EXPONENTIAL">指数退避</a-select-option>
                <a-select-option value="LINEAR">线性退避</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 步骤编辑器 -->
        <a-form-item label="执行步骤" name="steps">
          <div class="steps-editor">
            <a-button @click="addStep" type="dashed" block>
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加步骤
            </a-button>

            <div v-if="behaviorForm.steps" class="steps-list">
              <div
                v-for="(step, index) in behaviorForm.steps"
                :key="step.id"
                class="step-item"
              >
                <a-row :gutter="8">
                  <a-col :span="4">
                    <a-input v-model:value="step.id" placeholder="步骤ID" />
                  </a-col>
                  <a-col :span="4">
                    <a-select v-model:value="step.type" placeholder="步骤类型">
                      <a-select-option value="API_CALL">
                        API调用
                      </a-select-option>
                      <a-select-option value="STATE_CHANGE">
                        状态变更
                      </a-select-option>
                      <a-select-option value="EVENT_EMIT">
                        事件发布
                      </a-select-option>
                      <a-select-option value="NOTIFICATION">
                        通知
                      </a-select-option>
                      <a-select-option value="VALIDATION">验证</a-select-option>
                      <a-select-option value="TRANSFORMATION">
                        转换
                      </a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="12">
                    <a-input
                      v-model:value="step.config"
                      placeholder="配置信息（JSON格式）"
                    />
                  </a-col>
                  <a-col :span="4">
                    <a-space>
                      <a-button
                        v-if="index > 0"
                        type="text"
                        @click="moveStep(index, 'up')"
                      >
                        ↑
                      </a-button>
                      <a-button
                        v-if="index < behaviorForm.steps.length - 1"
                        type="text"
                        @click="moveStep(index, 'down')"
                      >
                        ↓
                      </a-button>
                      <a-button type="text" danger @click="removeStep(index)">
                        <IconifyIcon icon="ant-design:delete-outlined" />
                      </a-button>
                    </a-space>
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </a-form-item>

        <!-- 事件配置 -->
        <a-form-item label="发布事件" name="emits">
          <div class="events-editor">
            <a-button @click="addEvent" type="dashed" block>
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加事件
            </a-button>

            <div v-if="behaviorForm.emits" class="events-list">
              <div
                v-for="(event, index) in behaviorForm.emits"
                :key="index"
                class="event-item"
              >
                <a-row :gutter="8">
                  <a-col :span="20">
                    <a-input
                      v-model:value="behaviorForm.emits[index]"
                      placeholder="事件类型"
                    />
                  </a-col>
                  <a-col :span="4">
                    <a-button type="text" danger @click="removeEvent(index)">
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </a-button>
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 行为预览模态框 -->
    <a-modal
      v-model:open="previewModalVisible"
      title="行为预览"
      width="700px"
      :footer="null"
    >
      <div v-if="previewBehaviorData" class="behavior-preview">
        <a-descriptions title="基本信息" :column="2">
          <a-descriptions-item label="ID">
            {{ previewBehaviorData.id }}
          </a-descriptions-item>
          <a-descriptions-item label="名称">
            {{ previewBehaviorData.name }}
          </a-descriptions-item>
          <a-descriptions-item label="类型">
            {{ getBehaviorKindLabel(previewBehaviorData.kind) }}
          </a-descriptions-item>
          <a-descriptions-item label="重试策略">
            {{ previewBehaviorData.retryPolicy || 'NONE' }}
          </a-descriptions-item>
        </a-descriptions>

        <a-divider />

        <a-descriptions title="执行步骤" :column="1">
          <a-descriptions-item label="步骤详情">
            <a-steps direction="vertical" size="small">
              <a-step
                v-for="(step, index) in previewBehaviorData.steps"
                :key="step.id"
                :title="`${index + 1}. ${step.id}`"
                :description="getStepDescription(step)"
              />
            </a-steps>
          </a-descriptions-item>
        </a-descriptions>

        <a-divider v-if="previewBehaviorData.emits?.length" />

        <a-descriptions
          v-if="previewBehaviorData.emits?.length"
          title="发布事件"
          :column="1"
        >
          <a-descriptions-item label="事件列表">
            <a-tag
              v-for="event in previewBehaviorData.emits"
              :key="event"
              color="blue"
              style="margin: 2px"
            >
              {{ event }}
            </a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.resource-behaviors {
  .behaviors-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      margin: 0;
    }
  }

  .behaviors-content {
    .behaviors-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
      gap: 16px;
    }

    .behavior-card {
      .behavior-info {
        margin-bottom: 12px;

        p {
          margin: 4px 0;
        }
      }

      .steps-preview {
        h4 {
          margin: 0 0 8px 0;
          font-size: 14px;
          font-weight: 600;
        }
      }
    }
  }

  .steps-editor,
  .events-editor {
    .steps-list,
    .events-list {
      margin-top: 12px;

      .step-item,
      .event-item {
        margin-bottom: 8px;
        padding: 8px;
        border: 1px solid #f0f0f0;
        border-radius: 4px;
        background: #fafafa;
      }
    }
  }

  .behavior-preview {
    .ant-steps {
      margin-top: 8px;
    }
  }
}
</style>
